﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Gasco.DataAccess;
using Gasco.Business.Services;

public partial class Controls_city_add : System.Web.UI.UserControl
{

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            LoadCountries();

            if (Request.QueryString["id"] != null)
                LoadCity();
        }
    }

    private void LoadCountries()
    {
        LookupService<country> countryService = new LookupService<country>();
        ddCountry.DataSource = countryService.GetAll();
        ddCountry.DataBind();
    }

    private void LoadCity()
    {
        CityService cityService = new CityService();
        int id = Convert.ToInt32(Request.QueryString["id"]);
        city c = cityService.GetCity(id);
        tbName.Text = c.name;
        ddCountry.SelectedValue = c.country_id.ToString();
    }

    protected void btnclose_Click(object sender, EventArgs e)
    {
        if (Request.QueryString["id"] == null)
            AddCity();
        else
            UpdateCity();

        Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script1", "<script>pageClose();</script>");
    }

   
    private void AddCity()
    {
        CityService cityService = new CityService();
        cityService.AddCity(new city { name = tbName.Text, country_id = Convert.ToInt32(ddCountry.SelectedValue) });
    }

    private void UpdateCity()
    {
        CityService cityService = new CityService();
        int id = Convert.ToInt32(Request.QueryString["id"]);
        city c = cityService.GetCity(id);
        c.name = tbName.Text;
        c.country_id = Convert.ToInt32(ddCountry.SelectedValue);

        cityService.UpdateCity(c);
    }
}
